/*
 * Copyright 2008 the Breachwalls OSS project and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package com.breachwalls.quasar.datatype;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;

import com.breachwalls.quasar.datatype.converter.DatatypeConverter;
import com.breachwalls.quasar.datatype.converter.DatatypeConverterNotFoundException;
import com.breachwalls.quasar.datatype.converter.GenericDateTimeConverter;
import com.breachwalls.quasar.datatype.converter.GenericDecimalConverter;
import com.breachwalls.quasar.datatype.converter.GenericEnumerationConverter;
import com.breachwalls.quasar.datatype.converter.GenericStringConverter;

/**
 * Hibernateでデータタイプを使用できるようにするためのユーザタイプの実装.
 * @author todoken
 * @version $Revision: 37 $
 */
public class GenericHibernateUserType implements UserType, ParameterizedType {

    /**
     * データタイプコンバータ.
     */
    private DatatypeConverter converter;

    /**
     * {@inheritDoc}
     */
    public void setParameterValues(final Properties parameters) {
        final String datatype = parameters.getProperty("datatype");
        if (StringUtils.isBlank(datatype)) {
            throw new IllegalArgumentException("Parameter not specified");
        }

        Class<?> clazz = null;
        try {
            clazz = Class.forName(datatype);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Datatype not found [" + clazz + "]");
        }

        if (!Datatype.class.isAssignableFrom(clazz)) {
            throw new IllegalArgumentException("Invalid datatype class [" + clazz + "]");
        }
        this.converter = createDatatypeConverter(clazz);
    }

    /**
     * データタイプコンバータのファクトリメソッド.
     * @param clazz 変換したいデータタイプ
     * @return 変換したいデータタイプを変換可能なデータタイプコンバータ
     */
    protected DatatypeConverter createDatatypeConverter(Class<?> clazz) {
        if (GenericEnumerationConverter.isSupported(clazz)) {
            return new GenericEnumerationConverter(clazz);
        }
        if (GenericStringConverter.isSupported(clazz)) {
            return new GenericStringConverter(clazz);
        }
        if (GenericDateTimeConverter.isSupported(clazz)) {
            return new GenericDateTimeConverter(clazz);
        }
        if (GenericDecimalConverter.isSupported(clazz)) {
            return new GenericDecimalConverter(clazz);
        }

        throw new DatatypeConverterNotFoundException("[" + clazz + "] DatatypeConverter not found.");
    }

    /**
     * {@inheritDoc}
     */
    public int[] sqlTypes() {
        return this.converter.getSqlTypes();
    }

    /**
     * {@inheritDoc}
     */
    public Class<?> returnedClass() {
        return this.converter.getConvertedClass();
    }

    /**
     * {@inheritDoc}
     */
    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException {
        return this.converter.nullSafeGet(rs, names[0]);
    }

    /**
     * {@inheritDoc}
     */
    public void nullSafeSet(PreparedStatement st, Object value, int index) throws SQLException {
        this.converter.nullSafeSet(st, value, index);
    }

    /**
     * {@inheritDoc}
     */
    public boolean isMutable() {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    public Object assemble(final Serializable cached, final Object owner) {
        return cached;
    }

    /**
     * {@inheritDoc}
     */
    public Serializable disassemble(final Object value) {
        return (Serializable) value;
    }

    /**
     * {@inheritDoc}
     */
    public Object deepCopy(final Object value) {
        return value;
    }

    /**
     * {@inheritDoc}
     */
    public Object replace(final Object original, final Object target, final Object owner) {
        return original;
    }

    /**
     * {@inheritDoc}
     */
    public int hashCode(final Object x) {
        return x.hashCode();
    }

    /**
     * {@inheritDoc}
     */
    public boolean equals(final Object x, final Object y) {
        if (x == y) {
            return true;
        }
        if (x == null || y == null) {
            return false;
        }
        return x.equals(y);
    }

}
